package com.yoyo.yoyoplat.sdk;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.dollkey.hdownload.activity.AdWebViewActivity;
import com.dollkey.hdownload.serv.DownLoadNormalService;
import com.google.gson.Gson;
import com.yoyo.yoyoplat.base.ApiConstants;
import com.yoyo.yoyoplat.bean.ARequestBean;
import com.yoyo.yoyoplat.bean.AdInfoBean;
import com.yoyo.yoyoplat.bean.AppBean;
import com.yoyo.yoyoplat.bean.ImgsBean;
import com.yoyo.yoyoplat.bean.ResponseBean;
import com.yoyo.yoyoplat.util.HttpUtils;

import java.util.List;

public class NativeResponseImpl implements YYNativeResponse {
    private static final String TAG = "NativeResponseImpl";
    private AdInfoBean.DO mAdInfoBean;
    private int width;
    private int height;

    private int downX;
    private int downY;
    private int upX;
    private int upY;
    private ARequestBean mARequestBean;
    private ChooseByClickListener mChooseByClickListener;

    public NativeResponseImpl(AdInfoBean.DO adInfoBean, ARequestBean requestBean, ChooseByClickListener listener) {
        mAdInfoBean = adInfoBean;
        mARequestBean = requestBean;
        mChooseByClickListener = listener;
    }

    @Override
    public String getTitle() {
        return mAdInfoBean.getTitle();
    }

    @Override
    public String getSubTitle() {
        return mAdInfoBean.getSubTitle();
    }

    @Override
    public String getIconUrl() {
        return mAdInfoBean.getAdIcon();
    }

    @Override
    public List<ImgsBean> getImgList() {
        return mAdInfoBean.getImgs();
    }

    @Override
    public int getCType() {
        return mAdInfoBean.getCType();
    }

    @Override
    public AppBean getApp() {
        return mAdInfoBean.getApp();
    }

    @Override
    public void onExposed(View v) {
        width = v.getMeasuredWidth();
        height = v.getMeasuredHeight();
        dot(mAdInfoBean.getId(), mAdInfoBean.getKey(), ApiConstants.TK_IMP, width, height);
        v.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent ev) {
                switch (ev.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = (int) ev.getRawX();
                        downY = (int) ev.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        upX = (int) ev.getRawX();
                        upY = (int) ev.getRawY();
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void handleClick(View v) {
        dot(mAdInfoBean.getId(), mAdInfoBean.getKey(), ApiConstants.TK_CLK, width, height, downX, downY, upX, upY);
        mChooseByClickListener.onChoose(this);
        Context context = v.getContext();
        if (mAdInfoBean.getCType() == AdInfoBean.TYPE_H5) {
            AdWebViewActivity.newInstance(context, mAdInfoBean.getLandingPage().getTargetUrl(), false);
            return;
        }
        AppBean app = mAdInfoBean.getApp();
        if (app != null) {
            String deeplinkUrl = app.getDeeplinkUrl();
            switch (mAdInfoBean.getCType()) {
                case AdInfoBean.TYPE_DOWNLOAD:
                    context.startService(new Intent(context, DownLoadNormalService.class)
                            .putExtra(DownLoadNormalService.PARAM_APK_URL, deeplinkUrl)
                            .putExtra(DownLoadNormalService.PARAM_APK_NAME, deeplinkUrl.substring(deeplinkUrl.lastIndexOf("/"))));
                    break;
                case AdInfoBean.TYPE_MARKET:
                case AdInfoBean.TYPE_ACTION:
                    Uri destinationURI = Uri.parse(deeplinkUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, destinationURI);
                    if (deviceCanHandleIntent(context, intent)) {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
                    break;
            }
        }
    }

    public boolean deviceCanHandleIntent(Context context, Intent intent) {
        try {
            PackageManager mPm = context.getPackageManager();
            List<ResolveInfo> activities = mPm.queryIntentActivities(intent, 0);
            return !activities.isEmpty();
        } catch (Exception e) {
            return false;
        }
    }

    protected void dot(int dotType) {
        dot(mARequestBean.getId(), mARequestBean.getKey(), dotType, width, height);
    }

    private void dot(String id, String key, int dotType, int width, int height) {
        dot(id, key, dotType, width, height, null, null, null, null);
    }

    private void dot(String id, String key, int dotType, int width, int height, Integer downX, Integer downY, Integer upX, Integer upY) {
        resetClickPosition();
        mARequestBean.setId(id);
        mARequestBean.setKey(key);
        mARequestBean.setReportTypeCode(dotType);
        mARequestBean.setWidth(width);
        mARequestBean.setHeight(height);
        if (dotType == ApiConstants.TK_CLK) {
            mARequestBean.setDownX(downX);
            mARequestBean.setDownY(downY);
            mARequestBean.setUpX(upX);
            mARequestBean.setUpY(upY);
        }
        StringBuilder sb = HttpUtils.map2KeyValue(ApiConstants.getUrlMap());
        HttpUtils.doHttpRequest(ApiConstants.POST, ApiConstants.dotByPnames, sb.substring(0, sb.length() - 1),
                new Gson().toJson(mARequestBean), true, ResponseBean.class, new HttpUtils.ObjectCallback<ResponseBean>() {
                    @Override
                    public void onSuccess(ResponseBean responseBean) {
                        Log.e(TAG, String.valueOf(responseBean.getCode().equals(ApiConstants.SUCCESS) ? responseBean.getData().getCorrectReportTypeCode() : responseBean.getError()));
                    }

                    @Override
                    public void onFailure(int code, Exception e) {
                        Log.e(TAG, e.getCause().getMessage());
                    }
                });
    }

    private void resetClickPosition() {
        if (mARequestBean != null) {
            mARequestBean.setDownX(null);
            mARequestBean.setDownY(null);
            mARequestBean.setUpX(null);
            mARequestBean.setUpX(null);
        }
    }

    public interface ChooseByClickListener {
        void onChoose(NativeResponseImpl nativeResponse);
    }

}
